package com.tastespot.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tastespot.mapper.UserMapper;
import com.tastespot.model.dto.Result;
import com.tastespot.model.dto.ScrollResult;
import com.tastespot.model.dto.UserDTO;
import com.tastespot.model.entity.Blog;
import com.tastespot.mapper.BlogMapper;
import com.tastespot.model.entity.Follow;
import com.tastespot.model.entity.User;
import com.tastespot.service.IBlogService;
import com.tastespot.service.IFollowService;
import com.tastespot.service.IUserService;
import com.tastespot.utils.SystemConstants;
import com.tastespot.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

import static com.tastespot.constants.RedisConstants.BLOG_LIKED_KEY;
import static com.tastespot.constants.RedisConstants.FEED_KEY;
import static com.tastespot.constants.SystemConstants.DEFAULT_PAGE_SIZE;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {
    @Resource
    private IUserService userService;

    @Resource
    private UserMapper userMapper;

    @Resource
    private IFollowService followService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 保存完探店笔记后，获得到当前笔记的粉丝，然后把数据推送到粉丝的redis中去
     */
    @Override
    public Result saveBlog(Blog blog) {
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        // 1. 保存探店博文
        save(blog);
        // 2. 获得到当前笔记的粉丝
        List<Follow> follows = followService.query()
                .eq("follow_user_id", user.getId())
                .list();
        // 3. blogId推送到粉丝的redis中
        for(Follow follow : follows){
            Long userId = follow.getUserId();
            String redisKey = FEED_KEY + userId;
            //                               zadd key val score
            stringRedisTemplate.opsForZSet().add(redisKey, blog.getId().toString(), System.currentTimeMillis());
        }
        return Result.ok(blog.getId());
    }

    /**
     * 点赞博文
     * @param blogId
     * @return
     */
    @Override
    public Result likeBlog(Long blogId) {
        // 1. 获取当前登录用户
        Long userId = UserHolder.getUser().getId();
        String redisKey = BLOG_LIKED_KEY + blogId;
        Double score = stringRedisTemplate.opsForZSet().score(redisKey, userId.toString());
        Boolean isSuccess;
        // 2.1 未点赞
        if(Objects.isNull(score)){
            // 2.1.1 blog表 liked字段 + 1
            isSuccess = this.update(new LambdaUpdateWrapper<Blog>()
                    .eq(Blog::getId, blogId)
                    .setSql("liked = liked + 1"));
            // 2.1.2 将用户id存入redis set集合中
            if(isSuccess){
                // 数据库更新成功，更新缓存 zadd key value score
                stringRedisTemplate.opsForZSet().add(redisKey, userId.toString(), System.currentTimeMillis());
            }
        }else{
            // 2.2.1 blog表 liked字段 - 1
            isSuccess = this.update(new LambdaUpdateWrapper<Blog>()
                    .eq(Blog::getId, blogId)
                    .setSql("liked = liked - 1"));
            // 2.2.2 将用户id 从redis set集合中删除
            if(isSuccess){
                stringRedisTemplate.opsForZSet().remove(redisKey, userId.toString());
            }
        }
        return Result.ok();
    }

    /**
     * 查询所有点赞博客的用户
     * @param blogId
     * @return
     */
    @Override
    public Result queryBlogLikes(Long blogId) {
        String redisKey = BLOG_LIKED_KEY + blogId;
        // 查询top5的点赞用户
        Set<String> top5 = stringRedisTemplate.opsForZSet().range(redisKey, 0, 4);
        if(top5 == null || top5.size() == 0){
            return Result.ok(Collections.emptyList());
        }
        List<Long> userIds = top5.stream().map(Long::valueOf).collect(Collectors.toList());
        // 按照userId先后顺序查找UserDTO
        List<UserDTO> userDTOList = userMapper.queryUserOrderById(userIds);
        // 打印 userDTOList 日志信息
        log.info("userDTOList: {}", userDTOList);
        return Result.ok(userDTOList);
    }

    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = this.query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog ->{
            queryUserByBlog(blog);
            isBlogLiked(blog);
        });
        return Result.ok(records);
    }

    /**
     * 根据id查询博客
     * @param id
     * @return
     */
    @Override
    public Result queryBlogById(Long id) {
        Blog blog = this.getById(id);
        if (Objects.isNull(blog)) {
            return Result.fail("笔记不存在");
        }
        // 设置blog里的用户属性和isLike属性
        queryUserByBlog(blog);
        isBlogLiked(blog);
        return Result.ok(blog);
    }

    private void queryUserByBlog(Blog blog) {
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }

    /**
     * 判断当前用户是否点赞该博客
     */
    private void isBlogLiked(Blog blog){
        // 注意：此函数会在主页中用到，用户无需登录
        UserDTO userDTO = UserHolder.getUser();
        if(Objects.isNull(userDTO)){
            // 当前用户未登录，无需查询点赞
            return;
        }
        // 去redis里面查询是否有用户id
        Long userId = userDTO.getId();
        String redisKey = BLOG_LIKED_KEY + blog.getId();
        Double score = stringRedisTemplate.opsForZSet().score(redisKey, userId.toString());
        blog.setIsLike(Objects.nonNull(score));
    }

    /**
     * note 9: 滚动分页查询难点
     * 关注推送页面的分页查询
     * zset: (redisKey, blogId, timestamp)
     * @param lastTimeStamp 上一次查询时的最小时间戳
     * @param offset 本次页面中数据 score最小值的重复次数
     * 根据 lastTimeStamp + offset来确定【起始下标】
     * @return
     * List<Blog>:小于指定时间戳的笔记集合
     * minTime：本次查询的推送的最小时间戳
     * offset：偏移量
     */
    @Override
    public Result queryBlogOfFollow(Long lastTimeStamp, Integer offset) {
        Long userId = UserHolder.getUser().getId();
        String redisKey = FEED_KEY + userId;
        // 其中min max表示分数范围, 由于是从大到小排序, lastId即本次查询的maxScore无需关心min, 赋值0即可
        // 1.查询收件箱 ZREVRANGEBYSCORE key Max Min LIMIT offset pageSize
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet()
                .reverseRangeByScoreWithScores(redisKey, 0, lastTimeStamp, offset, DEFAULT_PAGE_SIZE);
        if(CollectionUtils.isEmpty(typedTuples)){
            return Result.ok();
        }
        // 求出最小时间戳的重复次数，至少重复一次
        int nextOffset = 1;
        long minTime = 0;
        List<Long> blodIds = new ArrayList<>(typedTuples.size());
        // 2.解析数据 blogId、minTime（时间戳）、offset
        for(ZSetOperations.TypedTuple<String> tuple : typedTuples){
            Long blogId = Long.valueOf(tuple.getValue());
            blodIds.add(blogId);
            long timestamp = tuple.getScore().longValue();
            if(timestamp == minTime){
                nextOffset++;
            }else{
                minTime = timestamp;
                nextOffset = 1;
            }
        }
        // (不做此判断若元素重复个数大于pgsize, 则无法获取后面的数据)
        nextOffset = minTime == lastTimeStamp ? offset+nextOffset : nextOffset;
        log.info("id = {}, minTime = {}, nextOffset = {}", userId, minTime, nextOffset);
        // 3. 查询blog列表(跟queryUserOrderById一样)此处未配置XML
        String idStr = StrUtil.join(",", blodIds);
        List<Blog> blogs = query().in("id", blodIds).last("ORDER BY FIELD(id," + idStr + ")").list();
        // 4. 填充blog信息
        for(Blog blog : blogs){
            queryUserByBlog(blog);
            isBlogLiked(blog);
        }
        ScrollResult r = new ScrollResult();
        r.setList(blogs);
        r.setMinTime(minTime);
        r.setOffset(nextOffset);
        return Result.ok(r);
    }
}
